'use strict';

const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Stream = require('@alicloud/darabonba-stream');

class Client {
  static createClient() {
    let config = new OpenApi.Config({
      accessKeyId: process.env.AccessKeyId,
      accessKeySecret: process.env.AccessKeySecret,
    });
    config.endpoint = `ocr-api.cn-hangzhou.aliyuncs.com`;
    return new OpenApi.default(config);
  }


  static createApiInfo() {
    let params = new OpenApi.Params({
      action: 'RecognizeIdcard',
      version: '2021-07-07',
      protocol: 'HTTPS',
      method: 'POST',
      authType: 'AK',
      style: 'V3',
      pathname: `/`,
      reqBodyType: 'json',
      bodyType: 'json',
    });
    return params;
  }

  static async main(args) {
    try{
    let client = Client.createClient();
    let params = Client.createApiInfo();
    let body = Stream.default.readFromFilePath(args);
    let runtime = new Util.RuntimeOptions({ });
    let request = new OpenApi.OpenApiRequest({
      stream: body,
    });
    let resp = await client.callApi(params, request, runtime);
    console.log("qetre",resp)
    let qq =  Util.default.toJSONString(resp)
    let qq1 = JSON.parse(qq).body.Data
    let qq2 = JSON.parse(qq1).data
    if(qq2["back"]){
      let backk = qq2["back"].data.validPeriod.split("-")[1]
      let tiim = new Date()<new Date(backk)
      return {time:tiim,type:"back"}
    }
    if(qq2["face"]){
      let facee = qq2["face"].data.name
      let carrd = qq2["face"].data.idNumber
      return {face:facee,card:carrd,type:"face"}
    }
  }catch(err){
    return undefined
  }
  }
}

module.exports = {main:Client.main}